package com.lyeducation.services.system;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.exceptions.ClientException;
import com.lyeducation.controllers.dto.system.BackstageSysUserDto;
import com.lyeducation.controllers.dto.system.InsertSysUserDto;
import com.lyeducation.core.base.*;
import com.lyeducation.core.system.SysUserService;
import com.lyeducation.entities.middle.SysRoleUserEntity;
import com.lyeducation.entities.middle.SysRoleUserEntityPK;
import com.lyeducation.entities.middle.SysUserImageEntity;
import com.lyeducation.entities.system.SysImageEntity;
import com.lyeducation.entities.system.SysRoleEntity;
import com.lyeducation.entities.system.SysUserEntity;
import com.lyeducation.entities.system.UserconnectionEntity;
import com.lyeducation.redis.RedisUtil;
import com.lyeducation.repository.redis.RedisRepository;
import com.lyeducation.repository.system.SysUserRepository;
import com.lyeducation.security.config.AuthenticationProcessingFilter;
import com.lyeducation.services.base.BaseCodeServiceImpl;
import com.lyeducation.util.EntityUtil;
import com.lyeducation.util.HttpUtils;
import com.lyeducation.util.MD5Util;
import com.lyeducation.util.StringUtils;
import com.lyeducation.util.aLiYunSms.ALiYunSmsUtil;
import com.lyeducation.util.controllerUtil.JsonConstans;
import com.lyeducation.util.controllerUtil.JsonResult;
import com.lyeducation.util.jwt.JwtUtil;
import com.lyeducation.util.mail.MailRecipient;
import com.lyeducation.util.mail.MailSendUtil;
import com.lyeducation.util.mail.TemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Service(value = "sysUserServiceImpl")
public class SysUserServiceImpl extends BaseCodeServiceImpl<SysUserEntity>
        implements SysUserService, UserDetailsService, SocialUserDetailsService {
  @Autowired
  private SystemProperties systemProperties;
  @Autowired private RedisRepository redisRepository;

  @Autowired private JwtUtil jwtUtil;

  @Autowired private SysUserRepository sysUserRepository;

  @Autowired private MailSendUtil mailSendUtil;

  //  @Autowired
//  private RedisTemplate redisTemplate;
  private RedisUtil redisUtil;

  @Autowired
  private ALiYunSmsUtil aLiYunSmsUtil;

  @Override
  public JsonResult saveOrUpdate(InsertSysUserDto insertSysUserDto, boolean checkRole)
          throws FileNotFoundException, ClientException, ExecutionException, InterruptedException {
    SysUserEntity sysUserEntity = null;
    Integer insertUserType = insertSysUserDto.getInsertUserType();
    if (StringUtils.isNotBlank(insertSysUserDto.getId())) {
      if (checkRole) {
        sysUserEntity = this.findUserCheckRole(insertSysUserDto.getId());
        if (sysUserEntity == null) {
          return JsonResult.putFail("操作非法");
        }
      } else {
        sysUserEntity = this.findById(insertSysUserDto.getId());
      }
    } else {
      //      Object code =
      //
      // redisTemplate.opsForHash().get(SysConstants.MOBILE_REGISTER_CODE_HASH.getValue(), mobile);
      //      if (code == null) {
      //        return JsonResult.putFail("手机验证码失效");
      //      }
      //      if (!StringUtils.equals(code.toString(), activeCode)) {
      //        return JsonResult.putFail("校验错误，请输入正确验证码");
      //      }
      sysUserEntity = new SysUserEntity();
      sysUserEntity.setEnabled(true);
      sysUserEntity.setAccountNonExpired(true);
      sysUserEntity.setAccountNonLocked(true);
      sysUserEntity.setCredentialsNonExpired(true);
      if (insertUserType == null || insertUserType > LOGINREGISTER.TYPE_REGISTER_MOBILE.ordinal()) {
        sysUserEntity.setEnabled(true);
      }
    }
    List<SysUserEntity> sysUserEntities = null;

    if (StringUtils.isNotBlank(insertSysUserDto.getName())
            && !StringUtils.equals(insertSysUserDto.getName(), sysUserEntity.getUsername())) {
      sysUserEntities = sysUserRepository.findByFiled("code", insertSysUserDto.getName());
      if (sysUserEntities.size() > 0) {
        return JsonResult.putFail("账号名已存在");
      }
    }
    if (!StringUtils.equals(insertSysUserDto.getNickName(), sysUserEntity.getName())) {
      sysUserEntities = sysUserRepository.findByFiled("name", insertSysUserDto.getNickName());
      if (sysUserEntities.size() > 0) {
        return JsonResult.putFail("昵称已存在");
      }
    }
    if (StringUtils.isNotBlank(insertSysUserDto.getMobile())
            && !StringUtils.equals(insertSysUserDto.getMobile(), sysUserEntity.getMobile())) {
      sysUserEntities = sysUserRepository.findByFiled("mobile", insertSysUserDto.getMobile());
      if (sysUserEntities.size() > 0) {
        return JsonResult.putFail("手机号已存在");
      }
    }
    if (StringUtils.isNotBlank(insertSysUserDto.getEmail())
            && !StringUtils.equals(insertSysUserDto.getEmail(), sysUserEntity.getEmail())) {
      sysUserEntities = sysUserRepository.findByFiled("email", insertSysUserDto.getEmail());
      if (sysUserEntities.size() > 0) {
        return JsonResult.putFail("邮箱已存在");
      }
    }
    if (StringUtils.isNotBlank(insertSysUserDto.getIdentityCard())
            && !StringUtils.equals(
            insertSysUserDto.getIdentityCard(), sysUserEntity.getIdentityCard())) {
      sysUserEntities =
          sysUserRepository.findByFiled("identityCard", insertSysUserDto.getIdentityCard());
      if (sysUserEntities.size() > 0) {
        return JsonResult.putFail("身份证已存在");
      }
    }
    insertSysUserDto.copyParamToSysUser(sysUserEntity);

    if (StringUtils.trimToNull(insertSysUserDto.getId()) == null) {
      List<SysRoleEntity> sysRoleEntities =
              sysUserRepository.findByFiled(
                      SysRoleEntity.class, "name", SysConstants.PROJECT_ROLE_USER.getValue());
      if (sysRoleEntities.size() != 1) {
        return JsonResult.putFail("无法获取普通用户权限");
      }
      sysUserRepository.save(sysUserEntity);

      Timestamp timestamp = new Timestamp(System.currentTimeMillis());
      if (StringUtils.trimToNull(insertSysUserDto.getImgBase64()) != null) {
        SysImageEntity imageEntity = new SysImageEntity();
        imageEntity.setId(TokenConstants.generateUserId());
        File file =
                HttpUtils.setBase64Data(
                        "userImage/" + sysUserEntity.getId(),
                        imageEntity.getId(),
                        insertSysUserDto.getImgBase64());
        String imgUrl =
                systemProperties.getProjectAddress()
                        + "/"
                        + file.toURI().getPath().split("classes/")[1];

        imageEntity.setUrl(file.getPath());
        imageEntity.setImgUrl(imgUrl);
        imageEntity.setSize(file.length());
        imageEntity.setName(file.getName());
        imageEntity.setCreateTime(timestamp);
        imageEntity.setUpdateTime(timestamp);
        String imageMimeType =
                insertSysUserDto.getImgBase64().split(",")[0].split(";")[0].split(":")[1];
        imageEntity.setMimeType(imageMimeType);
        imageEntity.setCreateId(sysUserEntity.getId());
        imageEntity.setUpdateId(sysUserEntity.getId());
        sysUserEntity.setPhoto(imgUrl);
        sysUserRepository.update(sysUserEntity);
        sysUserRepository.save(imageEntity);

        SysUserImageEntity sysUserImageEntity = new SysUserImageEntity();
        sysUserImageEntity.setImageId(imageEntity.getId());
        sysUserImageEntity.setUserId(sysUserEntity.getUserId());
        sysUserImageEntity.setCreateTime(timestamp);
        sysUserRepository.save(sysUserImageEntity);
      }
      SysRoleUserEntity sysRoleUserEntity = new SysRoleUserEntity();
      SysRoleEntity sysRoleEntity = sysRoleEntities.get(0);
      sysRoleUserEntity.setRoleId(sysRoleEntity.getId());
      sysRoleUserEntity.setUserId(sysUserEntity.getId());
      sysRoleUserEntity.setCreateTime(timestamp);
      sysUserRepository.save(sysRoleUserEntity);

      //      sysUserRepository.addMiddleTable(
      //          SysRoleUserEntity.class,
      //          "roleId",
      //          sysRoleEntity.getId(),
      //          "userId",
      //          sysUserEntity.getId(),
      //          new Timestamp(System.currentTimeMillis()));

      //      if (insertUserType != null) {
      //        if (insertUserType == LOGINREGISTER.TYPE_LOGIN_MAIL.ordinal()) {
      //          sendActiveEMail(sysUserEntity);
      //        } else if (insertUserType == LOGINREGISTER.TYPE_REGISTER_MOBILE.ordinal()) {
      //          Future<String> task =
      //                  aLiYunSmsUtil.sendCodeSms(
      //                          sysUserEntity.getMobile(),
      // LOGINREGISTER.TYPE_REGISTER_MOBILE.ordinal());
      //          while (true) {
      //            if (task.isDone()) {
      //              String responseCode = task.get();
      //              if (StringUtils.equals(responseCode, "OK")) {
      //                return JsonResult.putSuccess();
      //              }
      //              return JsonResult.putFail("短信发送超过限制");
      //            }
      //          }
      //        }
      //      }

    } else {
      if (StringUtils.trimToNull(insertSysUserDto.getImgBase64()) != null) {

        List<SysUserImageEntity> videoImageEntities =
                sysUserRepository.findByFiled(
                        SysUserImageEntity.class, "userId", insertSysUserDto.getId());
        if (videoImageEntities.size() > 1) {
          return JsonResult.putFail("截图个数错误:" + videoImageEntities.size());
        }
        SysImageEntity imageEntity = null;
        if (videoImageEntities.size() == 1) {
          imageEntity =
                  sysUserRepository.findById(
                          SysImageEntity.class, videoImageEntities.get(0).getImageId());
        }
        if (imageEntity == null) {
          imageEntity = new SysImageEntity();
          Timestamp timestamp = new Timestamp(System.currentTimeMillis());
          imageEntity.setCreateTime(timestamp);
          imageEntity.setCreateId(sysUserEntity.getId());

          //
          // imageEntity.setCreateId(SecurityPrincipalContext.getUserDetailsImpl().getId());
          //
          // imageEntity.setUpdateId(SecurityPrincipalContext.getUserDetailsImpl().getId());
          imageEntity.setUpdateTime(timestamp);
          imageEntity.setId(TokenConstants.generateUserId());
          SysUserImageEntity videoImageEntity = new SysUserImageEntity();
          videoImageEntity.setImageId(imageEntity.getId());
          videoImageEntity.setUserId(insertSysUserDto.getId());
          sysUserRepository.save(videoImageEntity);
        } else {
          File delFile = new File(imageEntity.getUrl());
          delFile.delete();
        }
        imageEntity.setUpdateId(sysUserEntity.getId());
        File file =
                HttpUtils.setBase64Data(
                        "userImage/" + insertSysUserDto.getId(),
                        imageEntity.getId(),
                        insertSysUserDto.getImgBase64());
        String imgUrl =
                systemProperties.getProjectAddress()
                        + "/"
                        + file.toURI().getPath().split("classes/")[1];
        String imageMimeType =
                insertSysUserDto.getImgBase64().split(",")[0].split(";")[0].split(":")[1];
        sysUserEntity.setPhoto(imgUrl);
        imageEntity.setMimeType(imageMimeType);
        imageEntity.setUrl(file.getPath());
        imageEntity.setImgUrl(imgUrl);
        imageEntity.setSize(file.length());
        imageEntity.setName(file.getName());
        sysUserRepository.save(imageEntity);
      }
      sysUserRepository.update(sysUserEntity);
    }

    return JsonResult.putSuccess();
  }

  public void sendActiveEMail(SysUserEntity sysUserEntity) throws FileNotFoundException {
    String param =
            systemProperties.getProjectAddress()
                    + "/sysUser/activeUserByEmailUrl/"
                    + sysUserEntity.getId();
    //    File[] files = new File[2];
    //    files[0] = new File("C:\\Users\\WSF\\Desktop\\timg.jpg");
    //    files[1] = new File("C:\\Users\\WSF\\Desktop\\宽带.txt");
    File contentImage =
            ResourceUtils.getFile("classpath:templates/user/registration/img/lyEducation.png");
    TemplateMessage templateMessage = new TemplateMessage();
    templateMessage.setActiveMsg(param);
    String content = mailSendUtil.readTemplate(templateMessage, "user/registration/activeUrl.ftl");

    List<MailRecipient> infos = new ArrayList<>();
    //    subject不可随意填写会报554 垃圾邮件
    MailRecipient mailRecipient =
            MailRecipient.getMailInfo(
                    sysUserEntity.getEmail(), null, null, "领英教育账号激活", content, contentImage, "a", null);
    Future<Boolean> task2 = mailSendUtil.sendMail(mailRecipient);
    //    没有这行无法发送邮件
    //    while (true) {
    //      if (task2.isDone()) {
    //        break;
    //      }
    //    }
  }

  @Override
  public JsonResult doSaveOrUpdate(Map paramsMap) {
    try {
      String id = StringUtils.getMapKeyValue(paramsMap, "id");
      String code = StringUtils.getMapKeyValue(paramsMap, "code");
      boolean isExistCode = isExistCode(code, id);
      if (isExistCode) {
        return JsonResult.putFail(JsonConstans.ERR_CODE_EXISTS);
      }
      SysUserEntity sysUserEntity = null;
      if (StringUtils.isNotBlank(id)) {
        if (paramsMap.containsKey(SysConstants.PASSWORD)) {
          paramsMap.remove(SysConstants.PASSWORD);
        }
        sysUserEntity = sysUserRepository.findById(SysUserEntity.class, id);
        if (sysUserEntity == null) {
          return JsonResult.putFail(JsonConstans.ERR_NOT_EXISTED);
        }
        EntityUtil.putMapDataIntoEntity(paramsMap, sysUserEntity);
        sysUserRepository.update(sysUserEntity);
      } else {
        sysUserEntity = new SysUserEntity();
        EntityUtil.putMapDataIntoEntity(paramsMap, sysUserEntity);
        sysUserEntity.setPassword(MD5Util.encodeMD5(sysUserEntity.getPassword()));
        sysUserEntity.setIsDelete(Boolean.FALSE);
        sysUserRepository.save(sysUserEntity);
      }
      return JsonResult.putSuccess();
    } catch (Exception e) {
      e.printStackTrace();
      return JsonResult.putFail(JsonConstans.OPERATION_FAILURE);
    }
  }

  @Override
  public JsonResult getSysUserTable(int pageNo, int pageSize) {
    Map<String, Object> paramMap = new HashMap<>();
    paramMap.put("isDelete", false);
    paramMap.put("roleName", SysConstants.PROJECT_ROLE_USER.getValue());
    String sql =
            "select u.* from sys_user as u left join (sys_role_user as ru LEFT JOIN sys_role as r on ru.roleId=r.id)  on u.id=ru.userId where u.isDelete=:isDelete and r.name=:roleName";
    Map<String, Object> result =
            sysUserRepository.findPageByNativeQueryFileds(sql, paramMap, pageNo, pageSize);

    List<SysUserEntity> users = (List<SysUserEntity>) result.get(SysConstants.ROWS.getValue());
    List<BackstageSysUserDto> showUserDtos = new ArrayList<>();
    Map<String, Object> map = new HashMap<>();
    map.put("total", result.get(SysConstants.TOTAL.getValue()));
    for (SysUserEntity sysUserEntity : users) {
      BackstageSysUserDto backstageSysUserDto = new BackstageSysUserDto(sysUserEntity);
      backstageSysUserDto.setId(sysUserEntity.getId());
      showUserDtos.add(backstageSysUserDto);
    }
    map.put("users", showUserDtos);
    return JsonResult.putSuccess(map);
  }

  @Override
  public JsonResult updIsDeleteSysUser(boolean isDelete, String userId) {
    LinkedHashMap linkedHashMap = new LinkedHashMap<String, Object>();
    linkedHashMap.put("id", userId);
    LinkedHashMap valueMap = new LinkedHashMap<String, Object>();
    valueMap.put("isDelete", isDelete);
    StringBuffer hql = new StringBuffer();
    hql.append("as u set u.isDelete=:isDelete where u.id=:id");
    if (sysUserRepository.updateFileds(hql.toString(), linkedHashMap, valueMap) > 0) {
      return JsonResult.putSuccess();
    }
    if (isDelete) return JsonResult.putFail("未查询到该用户,删除失败!");
    else return JsonResult.putFail("未查询到该用户,恢复失败!");
  }

  @Override
  public JsonResult enabledSysUser(boolean enabled, String userId) {
    LinkedHashMap linkedHashMap = new LinkedHashMap<String, Object>();
    linkedHashMap.put("id", userId);
    LinkedHashMap valueMap = new LinkedHashMap<String, Object>();
    valueMap.put("enabled", enabled);
    StringBuffer hql = new StringBuffer();
    hql.append("as u set u.enabled=:enabled where u.id=:id");
    if (sysUserRepository.updateFileds(hql.toString(), linkedHashMap, valueMap) > 0) {
      return JsonResult.putSuccess();
    }
    //    select u.* from sys_user as u left join (sys_role_user as ru LEFT JOIN sys_role as r on
    // ru.roleId=r.id)  on u.id=ru.userId where u.isDelete=:isDelete and r.name=:roleName
    return JsonResult.putFail("未查询到该用户,禁用失败!");
  }

  public JsonResult delSysUser(String userId) {
    LinkedHashMap linkedHashMap = new LinkedHashMap<String, Object>();
    linkedHashMap.put("id", userId);
    StringBuffer hql = new StringBuffer();
    hql.append("as u set u.isDelete=true where u.id=:id");
    if (sysUserRepository.updateFileds(hql.toString(), linkedHashMap, null) > 0) {
      return JsonResult.putSuccess();
    }
    //    select u.* from sys_user as u left join (sys_role_user as ru LEFT JOIN sys_role as r on
    // ru.roleId=r.id)  on u.id=ru.userId where u.isDelete=:isDelete and r.name=:roleName
    return JsonResult.putFail("未查询到该用户,删除失败!");
  }

  //  @Transactional(readOnly = true)
  //  @Override
  //  public SysUserEntity getUserMapByCode(String code) {
  //    String sql = "SELECT u.* FROM sys_user u WHERE u.code =:code AND u.isDelete =0";
  //    Map<String, Object> conditionParams = new HashMap<>(1);
  //    conditionParams.put("code", code);
  //    List<SysUserEntity> userList =
  //            sysUserRepository.findByNativeQuery(sql, conditionParams);
  ////            sysUserRepository.findByNativeQuery(sql, conditionParams,
  // Transformers.aliasToBean(SysUserEntity.class));
  //
  //    if (userList.size() > 1) {
  //      throw new RuntimeException("login user has " + (userList.size()));
  //    }
  //    if (userList.size() != 0) {
  //      return userList.get(0);
  //    }
  //    return null;
  //  }

  //  @Override
  //  public JsonResult doLogin(Map paramsMap) {
  //    String usercode = StringUtils.getMapKeyValue(paramsMap, "usercode");
  //    String password = StringUtils.getMapKeyValue(paramsMap, "password");
  //    if (StringUtils.isBlank(usercode) || StringUtils.isBlank(password)) {
  //      return JsonResult.putFail(JsonConstans.ERR_WRONG_PARAM);
  //    } else {
  //      SysUserEntity user = this.getUserMapByCode(usercode);
  //      if (user != null) {
  //        String userPassword = user.getPassword();
  //        password = MD5Util.encodeMD5(password);
  //        if (userPassword.equals(password)) {
  //          SysUserEntity sysUserEntity =
  //                  this.findById(SysUserEntity.class, user.getId().toString());
  ////          sysUserEntity.setUserToken(TokenConstants.generateToken());
  //          this.update(sysUserEntity);
  ////          redisRepository.delSession(user.get.toString());
  ////          userMap.put("userToken", sysUserEntity.getUserToken());
  //          userMap.remove("password");
  //          redisRepository.setSession(userMap);
  //          return JsonResult.putSuccess(userMap);
  //        } else {
  //          return JsonResult.putFail(JsonConstans.ERR_USER_PASSORD_NOTEQUAL);
  //        }
  //      } else {
  //        return JsonResult.putFail(JsonConstans.ERR_USER_PASSORD_NOTEQUAL);
  //      }
  //    }
  //  }

  @Override
  public boolean layout(HttpServletRequest request) {
    boolean isLayout = false;
    String userAccessToken = request.getHeader(SysConstants.USER_ACCESS_TOKEN.getValue());
    if (StringUtils.isNotBlank(userAccessToken)) {
      isLayout = redisRepository.delSession(userAccessToken);
    }
    return isLayout;
  }

  @Override
  public JsonResult addUserRole(Map paramsMap) {

    String roleIds = StringUtils.getMapKeyValue(paramsMap, "roleIds");
    String userId = StringUtils.getMapKeyValue(paramsMap, "userId");
    if (StringUtils.isBlank(userId) || StringUtils.isBlank(roleIds)) {
      return JsonResult.putFail(JsonConstans.ERR_WRONG_PARAM);
    }
    for (String roleId : roleIds.split(",")) {
      SysRoleUserEntityPK sysRoleUserEntityPK = new SysRoleUserEntityPK();
      sysRoleUserEntityPK.setRoleId(roleId);
      sysRoleUserEntityPK.setUserId(userId);
      SysRoleUserEntity sysRoleUserEntity =
          sysUserRepository.findByIdClass(new SysRoleUserEntity(), sysRoleUserEntityPK);
      if (sysRoleUserEntity == null) {
        sysRoleUserEntity = new SysRoleUserEntity();
        sysRoleUserEntity.setRoleId(roleId);
        sysRoleUserEntity.setUserId(userId);
        sysRoleUserEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
        sysUserRepository.save(sysRoleUserEntity);
      }
    }
    //    sysRoleUserRepository.deleteByRoleUserId(userId, roleIds);
    return JsonResult.putSuccess();
  }

  @Override
  public List<SysRoleEntity> userRoleList(String uId) {

    return null;
  }

  @Override
  public void updUserParamByLoginSuccess(HttpServletRequest httpServletRequest)
      throws UnknownHostException {
    sysUserRepository.updUserParamByLoginSuccess(httpServletRequest);
  }

  @Override
  public JsonResult activeUser(String primaryKey, int activeType) {
    LinkedHashMap linkedHashMap = new LinkedHashMap<String, Object>();
    LinkedHashMap valueMap = new LinkedHashMap<String, Object>();
    valueMap.put("enabled", true);
    StringBuffer hql = new StringBuffer();
    hql.append("as u set u.enabled=:enabled where u.");
    if (activeType == LOGINREGISTER.TYPE_LOGIN_MAIL.ordinal()) {
      hql.append("id=:id");
      linkedHashMap.put("id", primaryKey);
    } else if (activeType == LOGINREGISTER.TYPE_REGISTER_MOBILE.ordinal()) {
      hql.append("mobile=:mobile");
      linkedHashMap.put("mobile", primaryKey);
    } else {
      return JsonResult.putFail("账号激活类型错误");
    }
    if (sysUserRepository.updateFileds(hql.toString(), linkedHashMap, valueMap) > 0) {
      return JsonResult.putSuccess();
    }
    return JsonResult.putFail();
  }

  //  @Override
  //  public void updUserParamByLoginOut(HttpServletRequest httpServletRequest)
  //      throws UnknownHostException {
  //    loginSuccessOutParamSet(false, httpServletRequest);
  //  }

  //  private void loginSuccessOutParamSet(
  //      boolean loginSuccessOut, HttpServletRequest httpServletRequest) throws
  // UnknownHostException {
  //    LinkedHashMap<String, Object> paramMap = new LinkedHashMap();
  //    SysUserEntity user = SysUserUtils.getCurrentSysUser();
  //    Timestamp nowTime = new Timestamp(System.currentTimeMillis());
  //    paramMap.put("loginTime", nowTime.toString());
  //    if (loginSuccessOut) {
  //      paramMap.put("updateTime", nowTime.toString());
  //    } else {
  //      paramMap.put("loginOutTime", nowTime.toString());
  //    }
  //    paramMap.put("updateId", SysUserUtils.getCurrentSysUser().getId());
  //    paramMap.put("loginIp", IpUtil.getIpAddrByNginx(httpServletRequest));
  //    paramMap.put("id", user.getId());
  //    sysUserRepository.updateFileds(paramMap);
  //  }

  public UserDetails loadUserById(String id) {
    return sysUserRepository
            .setLoginUserRoleMenu(
                    sysUserRepository.getUserByIdCodeEmailMobile(SysConstants.ID_CODE.getValue(), id))
            .createUserDetailsImpl();
  }
  /**
   * 如果jwtToken存在且不过期这里不应该执行查询账号操作而是根据token生成账户，修改账户操作就必须查询最新数据
   *
   * @param s username
   * @return
   * @throws UsernameNotFoundException
   */
  @Transactional(readOnly = true)
  @Override
  public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
    HashMap<String, String> map = JSON.parseObject(s, HashMap.class);
    String username = map.get(SysConstants.USERNAME.getValue());
    username = StringUtils.trimToNull(username);
    String loginType = map.get(AuthenticationProcessingFilter.SPRING_SECURITY_FORM_LOGIN_TYPE);
    if (StringUtils.isNotBlank(loginType)
            && (StringUtils.equals(
            loginType, String.valueOf(LOGINSAVEUSERTYPE.LOGIN_USER_BY_MOBILE_CODE.ordinal())))) {
      //     邮箱,手机号加验证码|| StringUtils.equals(loginType, "2")
      String activeCode = null;
      //      if (StringUtils.equals(loginType, "2")) {
      //        activeCode =
      // redisTemplate.opsForHash().get(SysConstants.EMAILACTIVECODEHASH.getValue(), username);
      //      } else {
//      Object codeTimeOutObj =
//              redisTemplate.opsForHash().get(SysConstants.MOBILE_ACTIVE_CODE_HASH.getValue(), username);
      Object codeTimeOutObj =
              redisUtil.hget(SysConstants.MOBILE_ACTIVE_CODE_HASH.getValue(), username);
      //      }
      if (codeTimeOutObj == null) {
        throw new RuntimeException("未查询到该手机登录码");
      } else {
        Object[] codeTimeOutArray = (Object[]) codeTimeOutObj;
        activeCode = codeTimeOutArray[0].toString();
        long timeOut = (long) codeTimeOutArray[1];
        if (timeOut < System.currentTimeMillis()) {
//          redisTemplate
//                  .opsForHash()
//                  .delete(SysConstants.MOBILE_ACTIVE_CODE_HASH.getValue(), username);
          redisUtil.hdel(SysConstants.MOBILE_ACTIVE_CODE_HASH.getValue(), username);
          throw new RuntimeException("手机验证码过期");
        }
      }
      String activeCodeByUser =
              map.get(AuthenticationProcessingFilter.SPRING_SECURITY_FORM_PASSWORD_KEY);
      if (StringUtils.equals(activeCodeByUser, activeCode)) {
        //        if (StringUtils.equals(loginType, "0")) {
        //          sysUserEntity =
        // sysUserRepository.getUserByCodeEmailMobile(SysConstants.EMAIL.toString(), username);
        //        } else {
        //        if (StringUtils.equals(loginType, "1")) {        }
        SysUserEntity sysUserEntity =
                sysUserRepository.getUserByIdCodeEmailMobile(SysConstants.MOBILE.toString(), username);
        sysUserEntity.setPassword(new BCryptPasswordEncoder().encode(activeCode));
        return sysUserEntity;
      } else {
        throw new RuntimeException("请输入正确的验证码");
      }
    } else if (StringUtils.isNotBlank(loginType)
            && StringUtils.equals(
            loginType,
            String.valueOf(LOGINSAVEUSERTYPE.LOGIN_SAVE_USER_TYPE_BY_MOBILE.ordinal()))) {
      return sysUserRepository.getUserByIdCodeEmailMobile(SysConstants.MOBILE.toString(), username);
    } else if (StringUtils.isNotBlank(loginType)
            && StringUtils.equals(
            loginType, String.valueOf(LOGINSAVEUSERTYPE.LOGIN_SAVE_USER_TYPE_BY_EMAIL.ordinal()))) {
      return sysUserRepository.getUserByIdCodeEmailMobile(SysConstants.EMAIL.toString(), username);
    } else {
      //      String jwtToken = map.get(JwttokenconfigEnum.jwtToken.getValue());
      //      if (StringUtils.isBlank(username) && StringUtils.isNotBlank(jwtToken)) {
      //        try {
      //          Map jwtTokenMap = jwtUtil.validateToken(jwtToken);
      //          if (jwtTokenMap != null) {
      //            String jti = jwtTokenMap.get(JwttokenconfigEnum.jti.getValue()).toString();
      //            String redisJwtToken = jwtUtil.getJwtTokenByRedisHash(jti);
      //            if (!StringUtils.equals(jwtToken, redisJwtToken)) {
      //              return null;
      //            }
      //            return UserDetailsImpl.createUserDetailByMap(jwtTokenMap);
      //          }
      //        } catch (Exception e) {
      //          return null;
      //        }
      //      }
      return sysUserRepository.getUserByIdCodeEmailMobile("code", username);
    }
  }

  //  private SysUserEntity getSysUserEntityByCode(String username) {
  //    /** 查询用户根据code=username */
  //    SysUserEntity user = getUserMapByCode(username);
  //    if (user == null) {
  //      return null;
  //    }
  //    // 查询用户权限,多个权限能同级但不能上下级
  //    Map paramMap = new HashMap();
  //    paramMap.put("userId", user.getId());
  //    String sql = "SELECT ru.* from sys_role_user ru where ru.userId=:userId";
  //    List<SysRoleUserEntity> resRoleUser = sysUserRepository.findByNativeQuery(sql, paramMap,
  // Transformers.aliasToBean(SysRoleUserEntity.class));
  //    if (resRoleUser != null && resRoleUser.size() > 0) {
  //      paramMap.clear();
  //      List<String> paramList = new ArrayList();
  //      for (SysRoleUserEntity roleUser : resRoleUser) {
  //        paramList.add(roleUser.getRoleId());
  //      }
  //      paramMap.put("roleIdList", paramList);
  //      sql = "SELECT r.id,r.name from sys_role r where r.id in (:roleIdList)";
  //      List<SysRoleEntity> resRoleList =
  //              sysUserRepository.findByNativeQuery(sql, paramMap,
  // Transformers.aliasToBean(SysRoleEntity.class));
  //      //      查询该用户所有权限所有菜单
  //      if (resRoleList != null && resRoleList.size() > 0) {
  //        user.setRoles(resRoleList);
  //        sql = "SELECT * from sys_role_menu where roleId in(:roleIdList)";
  //        //                用户多个权限下权限不为上下级关系只能同级,或不同级等级差，
  //        // 只需要拿到最高级别权限的权限菜单中间表记录，如果最高级别权限有多个，则需要同时都获取到
  //        List<SysRoleMenuEntity> roleMenuList =
  //                sysUserRepository.findByNativeQuery(sql, paramMap,
  // Transformers.aliasToBean(SysRoleMenuEntity.class));
  //        if (roleMenuList != null && roleMenuList.size() > 0) {
  //          sql = "SELECT * from sys_menu where id in(:menuIdList)";
  //          paramMap.clear();
  //          paramList.clear();
  //          for (SysRoleMenuEntity roleMenu : roleMenuList) {
  //            paramList.add(roleMenu.getMenuId());
  //          }
  //          paramMap.put("menuIdList", paramList);
  //          List<SysMenuEntity> resMenuList =
  //                  sysUserRepository.findByNativeQuery(sql, paramMap,
  // Transformers.aliasToBean(SysMenuEntity.class));
  //          if (resMenuList != null && resMenuList.size() > 0) {
  //            //            将菜单menu归类到对应用户权限下
  //            resMenuList:
  //            for (SysMenuEntity menuEntity : resMenuList) {
  //              for (SysRoleMenuEntity sysRoleMenuEntity : roleMenuList) {
  //                if (menuEntity.getId().equals(sysRoleMenuEntity.getMenuId())) {
  //                  for (SysRoleEntity roleEntity : resRoleList) {
  //                    if (roleEntity.getId().equals(sysRoleMenuEntity.getRoleId())) {
  //                      HashSet<SysMenuEntity> menuSet = roleEntity.getMenus();
  //                      if (menuSet == null) {
  //                        menuSet = new HashSet<SysMenuEntity>();
  //                        roleEntity.setMenus(menuSet);
  //                      }
  //                      menuSet.add(menuEntity);
  //                      continue resMenuList;
  //                    }
  //                  }
  //                }
  //              }
  //            }
  //            // 将菜单menu累计上下级
  //
  //            //            登陆菜单
  //            user.setMenus(SysMenuEntity.upDownMenu(resMenuList));
  //          }
  //          //    需要更新登录成功后的参数信息无法传request获取ip，
  //          // 在sysUserRepository.update()无法获取当前线程的登陆者对象SysUserEntity u =
  //          // SysUserUtils.getCurrentSysUser();还没set进去，
  //          // system.currentTimeMillis()));
  //          //    在AuthenticationSuccessHandlerImpl登录成功处理类可以解决这些问题
  //          //    sysUserRepository.update(user);
  //        }
  //      }
  //    }
  //    return user;
  //  }
  @Override
  public SysUserEntity findUserCheckRole(String id) {
    SysUserEntity sysUserEntity = sysUserRepository.findById(id);
    if (sysUserEntity != null) {
      List<SysRoleUserEntity> sysRoleUserEntities =
          sysUserRepository.findByFiled(SysRoleUserEntity.class, "userId", sysUserEntity.getId());
      if (sysRoleUserEntities.size() == 1) {
        SysRoleEntity sysRoleEntity =
            sysUserRepository.findById(SysRoleEntity.class, sysRoleUserEntities.get(0).getRoleId());
        if (sysRoleEntity != null) {
          if (StringUtils.equals(
                  sysRoleEntity.getName(), SysConstants.PROJECT_ROLE_USER.getValue())) {
            return sysUserEntity;
          }
        }
      }
    }
    return null;
  }

  /**
   * @param s displayName
   * @return
   * @throws UsernameNotFoundException
   */
  @Override
  public SocialUserDetails loadUserByUserId(String s) throws UsernameNotFoundException {
//    Map queryMap = JSON.parseObject(s, HashMap.class);
//    List<SysUserEntity> sysUserEntities = sysUserRepository.findByFileds(queryMap);
    List<SysUserEntity> sysUserEntities = sysUserRepository.findByFiled("code", s);
    SysUserEntity sysUserEntity = null;
    if (sysUserEntities.size() == 1) {
      sysUserEntity = sysUserEntities.get(0);
    }

    if (sysUserEntity == null) {
      UserconnectionEntity userconnectionEntity =
              sysUserRepository.findByFiled(UserconnectionEntity.class, "userId", s).get(0);
      sysUserEntity = new SysUserEntity();
      sysUserEntity.setEnabled(true);
      sysUserEntity.setAccountNonExpired(true);
      sysUserEntity.setAccountNonLocked(true);
      sysUserEntity.setCredentialsNonExpired(true);
      sysUserEntity.setName(userconnectionEntity.getDisplayName());
//      sysUserEntity.setMobile();
      sysUserEntity.setPassword(new BCryptPasswordEncoder().encode("123456"));
      sysUserEntity.setCode(s);
      sysUserEntity.setId(TokenConstants.generateUserId());
//      sysUserEntity(userconnectionEntity.getUserId());
      sysUserRepository.save(sysUserEntity);
      List<SysRoleEntity> sysRoleEntities =
              sysUserRepository.findByFiled(
                      SysRoleEntity.class, "name", SysConstants.PROJECT_ROLE_USER.getValue());
      if (sysRoleEntities.size() != 1) {
        throw new RuntimeException("无法获取普通用户权限");
      }
//      SysRoleEntity sysRoleEntity = sysRoleEntities.get(0);
      SysRoleUserEntity sysRoleUserEntity = new SysRoleUserEntity();
      sysRoleUserEntity.setRoleId(sysRoleEntities.get(0).getId());
      sysRoleUserEntity.setUserId(sysUserEntity.getId());
      sysRoleUserEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
      sysUserRepository.save(sysRoleUserEntity);
    }
    return sysUserEntity;
  }
}
